<script setup>
import {ref} from 'vue'
import {Document, MoonNight, Setting, Sunny, SwitchButton, User, Wallet} from '@element-plus/icons-vue'
import 'element-plus/theme-chalk/dark/css-vars.css'
import router from "@/router/index.js";
import {ElLoading, ElMessage} from 'element-plus'
import {useThemeStore} from "@/stores/themeStore.js";
import Login from "@/components/loginView/login.vue"
import {useAutoStore} from "@/stores/autoStore.js"
import {useRememberStore} from "@/stores/rememberStore.js";
import {useTemporaryIdStore} from "@/stores/TemporaryIdStore.js"
import {useTokenStore} from "@/stores/tokenStore.js"
// import {temporaryIdStore}from"@/stores/TemporaryIdStore.js"
import {autoLoginService, logoutService, registerService, verifyService} from "@/api/user.js"
const autoStore = useAutoStore();
const rememberStore = useRememberStore()
const temporaryIdStore = useTemporaryIdStore()
const temId=useTemporaryIdStore()
const tokenStore = useTokenStore()
const activeIndex = ref('1')
const isLoggedIn = ref(false);
const notLoggedIn = ref(true);
const fullscreenLoading = ref(false)
const code = ref('')
let regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!%*?&@])[A-Za-z\d@!%*?&.]{8,}$/
const dialogTableVisible = ref(false)
const checkCode = (rule, value, callback) => {
    if (value === '') {
        callback(new Error("请输入验证码"))
    } else if (value !== code.value) {
        callback(new Error("验证码错误!"))
        imageVerify()
    } else {
        callback()
    }
}
const thePassword = (rule, value, callback) => {
    if (!regex.test(value)) {
        callback(new Error("至少要有一个大小写字母一个特殊字符(@!%*?&.)"))
    }
}
const checkRePassword = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次确认密码'))
    } else if (value !== registerData.value.password) {
        callback(new Error('请确保两次输入的密码一样'))
    } else {
        callback()
    }
}
const success = (message) => {
    ElMessage.success(message)

}
const AutoLogin = async () => {
   // const rememberStore = useRememberStore()
    const autoStore = useAutoStore()
    if (autoStore.auto) {
        //await
           const result =  await autoLoginService();
            const isAuto = result.data;
            isLogin.value.status = false
            loginData.value.userName=''
            loginData.value.password=''


    }
}
const logout = async () => {
    await logoutService()
    isLogin.value = false
    autoStore.setAuto(false)
    rememberStore.setRemember(false)
}
const rules = ({
    username: [
        {required: true, message: '请输入用户名', trigger: 'blur'},
        {min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur'}
    ],
    password: [
        {required: true, message: '请输入密码', trigger: 'blur'},
        {min: 8, max: 16, message: '长度为8~16位非空字符', trigger: 'blur'},
        {validator: thePassword, trigger: "blur"}
    ],
    rePassword: [
        {validator: checkRePassword, trigger: 'blur'}
    ]
})

const loginRule = {
    username: [
        {required: true, message: '请输入用户名', trigger: 'blur'},
    ],
    password: [
        {required: true, message: '请输入密码', trigger: 'blur'}
    ]
    ,
    code: [
        {validator: checkCode, trigger: 'blur'}
    ]
}
const toRegister = async () => {
    await registerService(registerData.value)
    success("注册成功")
    login.value.status = true
    clear()
}
const clearLogin = () => {
    if (!rememberStore.remember) {
        loginData.value.username = ''
        loginData.value.password = ''
        loginData.value.rePassword = ''
    }
    loginData.value.code = ''
}
const imageVerify = async () => {
    // const temporaryIdStore = useTemporaryIdStore()
    let result
    try {
        result = await verifyService(temporaryIdStore.temporaryid)
    } catch (err) {
        await verifyService(temporaryIdStore.temporaryid)
    }
    const codeResult = result.data
    img.value = codeResult.image;
    code.value = codeResult.code
    img.value = `data:image/jpeg;base64,${img.value}`
    if (temporaryIdStore.temporaryid === '') {
        temporaryIdStore.setTemporaryid(codeResult.temporaryId)
    }
}
const clear = () => {
    registerData.value = {
        username: '',
        password: '',
        rePassword: '',
    }
}
const login = async () => {

    loginData.value.temporaryId = temId.temporaryId
    const result = await loginService(loginData.value)
    success("登录成功")
    rememberStore.setRemember(loginData.value.isRemember)
    autoStore.setAuto(loginData.value.isAuto)
    tokenStore.setToken(result.data)
    isLogin.value = true
    loginVisible.value = false
    clearLogin()
}
const img = ref()
const isLogin = ref({
    status:false
    }

)
const registerData = ref({
    password:'',
    userName:'',
    rePassword:''
})
const loginData = ref({

    isAuto: false,
    isRemember: false,
    userName:'',
    password:'',
    code:'',
})
const openFullScreen = () => {
    const loading = ElLoading.service({
        lock: true,
        text: '切换中',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    setTimeout(() => {
        loading.close()
    }, 250)
}
const handleSelect = (key, keyPath) => {
    console.log(key, keyPath)
}
const themeStore = useThemeStore()
const circleUrl = ref('/src/assets/avatar.png')
const isDark = ref(themeStore.theme);
const dark = ref()
dark.value = isDark.value
const toggleDark = () => themeStore.setTheme(!dark.value)
const main_logo_src = ref("/src/assets/light_main_logo.svg")
const Register = () => {
    return true
}
const chageTheme = (val) => {
    const delay = 200; // 延迟时间，单位为毫秒

    setTimeout(() => {
        if (!val) {
            main_logo_src.value = "/src/assets/light_main_logo.svg";
            document.documentElement.setAttribute('theme', 'light');
            document.querySelector("html")?.classList.remove("dark");
            document.querySelector("html")?.classList.add("light");
        } else {
            main_logo_src.value = "/src/assets/dark_main_logo.svg";
            document.documentElement.setAttribute('theme', 'dark');
            document.querySelector("html")?.classList.remove("light");
            document.querySelector("html")?.classList.add("dark");
        }
    }, delay);
};
const handleOpen = (key, keyPath) => {
    console.log(key, keyPath)
}
const handleClose = (key, keyPath) => {
    console.log(key, keyPath)
}
router.push("/ai/chatgpt")
chageTheme(themeStore.theme)
</script>
<template>
    <div class="common-layout">
        <el-container class="layout-container">
            <el-dialog v-model="dialogTableVisible" draggable style:z-index="9999" title="注册登录" width="600">
                <Login :clear="clear" :clearLogin="clearLogin" :imageVerify="imageVerify" :img="img"
                       :isLogin="isLogin" :login="login" :loginData="loginData" :loginRule="loginRule"
                       :registerData="registerData"
                       :rules="rules" :toRegister="toRegister">
                </Login>
            </el-dialog>
            <el-header>
                <el-menu
                        :default-active="activeIndex"

                        :ellipsis="false"
                        class="el-menu-demo"
                        mode="horizontal"
                        @select="handleSelect"
                >
                    <el-menu-item index="0" style="width: 150px">
                        <img
                                :src="main_logo_src"
                                style="width: 70px"
                        />
                        <h2 class="title">我的AI助手</h2>
                    </el-menu-item>


                    <div class="flex-grow"/>

                    <!--                    <el-menu-item index="1">主页</el-menu-item>-->
                    <el-sub-menu index="2">
                        <template #title>
                            <el-avatar :size="50" :src="circleUrl"/>
                        </template>

                        <el-menu-item v-if="isLoggedIn" index="2-1">
                            <el-icon>
                                <User/>
                            </el-icon>
                            我的信息
                        </el-menu-item>
                        <el-menu-item v-if="isLoggedIn" index="2-2">
                            <el-icon>
                                <Wallet/>
                            </el-icon>
                            我的余额
                        </el-menu-item>
                        <div v-if="isLoggedIn">
                            <el-row align="middle">
                                <el-col :offset="2" :span="8" style="font-size: 15px">黑暗模式</el-col>
                                <el-col :span="6">
                                    <el-switch v-model="dark" v-loading.fullscreen.lock="fullscreenLoading"
                                               :active-icon="MoonNight"
                                               :inactive-icon="Sunny"
                                               active-color="var(--el-fill-color-dark)"
                                               inactive-color="var(--el-color-primary)"
                                               inline-prompt size="large"
                                               @change="toggleDark;chageTheme(dark);" @click="openFullScreen"/>
                                </el-col>
                            </el-row>
                        </div>
                        <el-divider v-if="isLoggedIn" class="divider"/>
                        <el-menu-item v-if="isLoggedIn" class="login-out" index="2-4" style="color: red">
                            <el-icon>
                                <SwitchButton/>
                            </el-icon>
                            退出登录
                        </el-menu-item>
                        <el-menu-item v-if="notLoggedIn" class="center-text">

                            <el-link :underline="false" @click="dialogTableVisible=true">登录/注册</el-link>


                        </el-menu-item>
                    </el-sub-menu>
                </el-menu>
            </el-header>
            <el-container>

                <el-aside class="aside-color" width="280px">
                    <el-row class="tac">
                        <el-col :span="24">
                            <el-menu
                                    class="el-menu-vertical-demo"
                                    default-active="/ai/chatgpt"
                                    router
                                    @close="handleClose"
                                    @open="handleOpen"
                            >
                                <el-menu-item index="/ai/chatgpt">
                                    <img src="@/assets/chatGPT.svg" width="25px">
                                    <span>ChatGPT</span>
                                </el-menu-item>
                                <el-menu-item index="/ai/stability">
                                    <el-icon>
                                        <document/>
                                    </el-icon>
                                    <span>Stability</span>
                                </el-menu-item>
                                <el-menu-item index="/ai/homework">
                                    <img src="@/assets/homework.svg" width="25px">
                                    <span>homework</span>
                                </el-menu-item>
                                <el-menu-item disabled index="4">
                                    <el-icon>
                                        <setting/>
                                    </el-icon>
                                    <span>更多</span>
                                </el-menu-item>
                            </el-menu>
                        </el-col>
                    </el-row>
                </el-aside>
                <el-container>

                    <el-main>
                        <div style="width: 100% ; height: 100% ">
                            <router-view></router-view>
                        </div>
                    </el-main>
                </el-container>
            </el-container>
        </el-container>
    </div>
</template>

<style lang="scss" scoped>
.el-link {
  margin-right: 8px;
}

.el-link .el-icon--right.el-icon {
  vertical-align: text-bottom;
}

.flex-grow {
  flex-grow: 1;
}

.login-out:active {
  background-color: lightcoral;
  color: #ff0000
}

.login-out {
  background-color: lightblue;
  color: #ffffff
}

.divider {
  margin-top: 8px;
  margin-bottom: 8px;
}

.layout-container {
  height: 100vh;

  .el-aside {
    .el-menu {
      border-right: none;
    }
  }
}

.el-footer {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #666;
}

.chatgpt-icon {
  background-image: url("src/assets/icons8-chatgpt-100.svg");
}

.mydiv {
  width: 0;
  height: 0;
  display: flex;
  flex-direction: column;
}

.el-link {
  margin-right: 8px;
}

.el-link .el-icon--right.el-icon {
  vertical-align: text-bottom;
}

.center-text {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>